/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-25 17:28:53
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-04-17 16:50:33
 * @FilePath: \vite-project\src\components\common\MenuTree.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Empty, Spin, Tree } from 'antd';
import React, { useImperativeHandle } from 'react';
import { useEffect, useState } from 'react';

interface MenuTreeProps {
	appId?: string | null;
	queryCondition?: string | null;
	onSelect: (_selectedKeys: any, e: any) => void;
	onUpdateTreeData: (data: any) => void;
	api: () => Promise<any>;
	fieldNamesTitle?: string;
	fieldNamesKey?: string;
	ref?: any;
	needAppId?: boolean;
	treeKeyInName?: string;
}

const MenuTree: React.FC<MenuTreeProps> = React.forwardRef(
	(
		{
			needAppId = false,
			appId = '',
			queryCondition = '',
			fieldNamesTitle = 'label',
			fieldNamesKey = 'id',
			onSelect = () => {},
			onUpdateTreeData = () => {},
			api,
			treeKeyInName = 'organizationTree',
		},
		ref,
	) => {
		// org tree
		const [menuTreeData, setMenuTreeData] = useState<{}[]>([]);
		const [menuTreeLoading, setMenuTreeLoading] = useState(false);

		const getMenuTreeData = async () => {
			setMenuTreeLoading(true);
			try {
				let res: any = await api?.();

				setMenuTreeData(
					res?.[treeKeyInName]
						? [
								{
									...res?.[treeKeyInName],
									isRoot: true,
								},
						  ]
						: [],
				);
				onUpdateTreeData(res?.[treeKeyInName] ? [res?.[treeKeyInName]] : []);
			} finally {
				setMenuTreeLoading(false);
			}
		};

		useEffect(() => {
			if ((needAppId && appId) || !needAppId) {
				getMenuTreeData();
			}
		}, [queryCondition, appId]);

		useImperativeHandle(
			ref,
			() => {
				return {
					refresh: getMenuTreeData,
				};
			},
			[],
		);

		return (
			<Spin spinning={menuTreeLoading}>
				{menuTreeData?.length ? (
					<Tree
						defaultExpandAll={true}
						showLine={true}
						showIcon={true}
						onSelect={onSelect}
						treeData={menuTreeData}
						fieldNames={{
							title: fieldNamesTitle,
							key: fieldNamesKey,
						}}
					/>
				) : (
					<Empty />
				)}
			</Spin>
		);
	},
);

export default MenuTree;
